import httplib2
from django.http import HttpResponse, Http404
from osgeo import ogr, osr

def get_arc2_from_lonlat(lon,lat):
    wkt = 'POINT(%s %s)' % (lon,lat)
    p = ogr.CreateGeometryFromWkt(wkt) 
    wgs84 = osr.SpatialReference()
    arc = osr.SpatialReference()
    arc.ImportFromProj4('+proj=eqc +lat_ts=41.12682127 +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs')
    wgs84.ImportFromProj4('+proj=latlong +datum=wgs84')
    p.AssignSpatialReference(wgs84)
    p.TransformTo(arc)
    return p.GetX(),p.GetY()

def summary_proxy(request):
    try:
        lon = float(request.REQUEST['lon'])
        lat = float(request.REQUEST['lat'])
    except:
        return HttpResponse("Must provide lat and lon.", status=404)
   
    x,y = get_arc2_from_lonlat(lon,lat)

    url = "http://globalmarine.nceas.ucsb.edu/ca_xyquery?x=%s&y=%s" % (x,y)
    conn = httplib2.Http()
    resp, content = conn.request(url, "GET")
    return HttpResponse(content,status=resp['status'])

def summary_csv_proxy(request):
    try:
        x = float(request.REQUEST['x'])
        y = float(request.REQUEST['y'])
    except:
        return HttpResponse("Must provide x and y.", status=404)
   
    url = "http://globalmarine.nceas.ucsb.edu/ca_xyquery/datasummary.csv?x=%s&y=%s" % (x,y)
    conn = httplib2.Http()
    resp, content = conn.request(url, "GET")
    response = HttpResponse(content,status=resp['status'])
    response['Content-Disposition'] = 'attachment; filename=ca_current_data_summary.csv'
    return response
